package org.itzheng.itplayer

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.itzheng.and.activity.ItActivity
import org.itzheng.and.activity.SplashActivity
import org.itzheng.base.BaseFragment
import org.itzheng.itplayer.home.MainFragment

class MainActivity : ItActivity() {
    private val TAG = "MainActivity"
    override fun onCreate(savedInstanceState: Bundle?) {
        isRunning = true
        if (savedInstanceState == null) {
            //如果是状态改变就不用弹出启动页，这样就不会出现从上个界面回来会有启动页的效果
            SplashActivity.startActivity(this, AppSplashActivity::class.java)
        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setTranslucentStatus(true)
        setStatusBarDarkMode(true);
        supportFragmentManager.addOnBackStackChangedListener {
            //进栈出栈的监听，进出栈都会调用
            Log.w(TAG, "onBackStackChanged")
            if (mRemoveFragmentList.isNotEmpty()) {
                //如果不为空就一个一个进行移除,这里是移除finish的fragment
                for (fragment in mRemoveFragmentList) {
                    if (isStackTop(fragment)) {
                        onBackPressed()
                        //调用一个就结束了，因为只要进出站就会执行监听
                        break
                    }
                }
            }
            //移除完毕后，检测一下建站的
            setFragmentOnStackChangeListener()
        }
        startFragment(MainFragment.newInstance(), false)
    }

    var stackListenerJob: Job? = null

    /**
     *需要设置栈改变状态的只有第一个和第二个
     */
    private fun setFragmentOnStackChangeListener() {
        stackListenerJob?.cancel()
        stackListenerJob = lifecycleScope.launch(Dispatchers.Main) {
//            delay(100)
            val mFragment = getFragments();
            if (mFragment.size == 1) {
                (mFragment[0] as BaseFragment).setStackTopStatus(true)
            } else if (mFragment.size > 1) {
                (mFragment[mFragment.size - 1] as BaseFragment).setStackTopStatus(true)
                (mFragment[mFragment.size - 2] as BaseFragment).setStackTopStatus(false)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        setFragmentOnStackChangeListener()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (SplashActivity.isSplashEnd(requestCode, resultCode, data)) {
            //启动页结束
        }
        val mFragment = getFragments();
        for (frag in mFragment) {
            frag.onActivityResult(requestCode, resultCode, data)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        isRunning = false
    }
//    /**
//     * 当前栈内的fragment
//     */
//    private val mFragment = mutableListOf<BaseFragment>()

    /**
     * 跳转到 Fragment
     *
     * @param fragment
     */
    public fun startFragment(fragment: BaseFragment) {
        //默认都有动画，首页不需要动画
        startFragment(fragment, true)

    }

    /**
     * 最后启动的Activity，用于判断栈顶
     */
    private var lastStartFragment: BaseFragment? = null;

    /**
     * 将fragment添加到栈
     */
    public fun startFragment(fragment: BaseFragment, isAnim: Boolean) {
        //一跳转到新的，当前就不是栈顶
        val mFragment = getFragments()
        if (mFragment.isNotEmpty()) {
            (mFragment[mFragment.size - 1] as BaseFragment).setStackTopStatus(false);
        }


//        (@AnimatorRes @AnimRes int enter,
//        @AnimatorRes @AnimRes int exit, @AnimatorRes @AnimRes int popEnter,
//        @AnimatorRes @AnimRes int popExit
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (isAnim) {
            //需要设置动画就设置默认动画
            transaction.setCustomAnimations(
                    R.anim.anim_fragment_enter_right_to_center,
                    R.anim.anim_fragment_exit_center_to_left,
                    R.anim.anim_fragment_pop_enter_left_to_center,
                    R.anim.anim_fragment_pop_exit_center_to_right
            )
        }
        //用replace相当于当前界面只有一个fragment,优点，android:fitsSystemWindows="true"不会失效，
        // 缺点，由于只有一个fragment，上个Fragment必然退出,就是数据无法保存
        // 如果用add则后面的界面都无法设置 fitsSystemWindows
        fragment.stackId =
                transaction.add(R.id.container, fragment!!)
                        .addToBackStack("")
//            .addToBackStack(fragment.stackName)
                        .commitAllowingStateLoss()
//        mFragment.add(fragment)
        lastStartFragment = fragment;
    }

    /**
     * 返回键,方便fragment调用
     */
    fun onBack(view: View) {
        onBackPressed()
    }

    /**
     * fragment，用这个比较好，自己添加的，生命周期，还原不了
     */
    private fun getFragments(): List<BaseFragment> {
        val baseFragments = mutableListOf<BaseFragment>()
        for (frag in supportFragmentManager.fragments) {
            if (frag is BaseFragment) {
                baseFragments.add(frag)
            }
        }
        return baseFragments
    }

    override fun onBackPressed() {
        hideSoftInput()
        var mFragments = getFragments();
        if (supportFragmentManager.backStackEntryCount > 1) {
            if (mFragments.isNotEmpty()) {
                val fragment = mFragments[mFragments.size - 1] as BaseFragment
                if (!fragment.onBackPressed()) {//不拦截，直接弹出
                    if (fragment == lastStartFragment) {
                        //被移除，肯定不是栈顶了
                        lastStartFragment = null;
                    }
                    //移出栈，就不是栈顶了
                    fragment.setStackTopStatus(false)
//                    mFragment.remove(fragment)
                    supportFragmentManager.popBackStack() //若栈中有很多碎片只会向上弹一个
                    mFragments = getFragments();
                    //这样，上一个就是栈顶了
                    if (mFragments.isNotEmpty()) {
                        val top = mFragments[mFragments.size - 1] as BaseFragment
                        top.setStackTopStatus(true)
                    }
                }
            }
        } else if (mFragments.size == 1) {
            //最后一个直接关闭
            val fragment = mFragments[0] as BaseFragment
            if (fragment.onBackPressed()) {
                //如果最后一个拦截
                return
            }
            //这里已经没有拦截的，判断是否退出
            if (!doubleClick()) {
                showToast("再按一次退出")
                return
            }
            finish()
        } else {
            finish()
        }
    }

    var lastExitClickTime = 0L

    /**
     * 判断是否双击
     */
    private fun doubleClick(): Boolean {
        val current = System.currentTimeMillis()
        val isDoubleClick = lastExitClickTime + 2000 > current
        lastExitClickTime = current
        return isDoubleClick
    }

    /**
     * 判断 fragment 是否是栈顶
     */
    private fun isStackTop(fragment: BaseFragment): Boolean {
        val mFragment = getFragments()
        if (mFragment.isEmpty()) {
            return false
        }
        if (lastStartFragment != null) {
            //说明，最后一个启动的还没消失,按道理，最后启动的就是栈顶
            return lastStartFragment == fragment
        }
        return (mFragment.get(mFragment.size - 1) == fragment)
    }

    //List<BaseFragment> mRemoveFragmentList=
    private val mRemoveFragmentList = mutableListOf<BaseFragment>()

    /**
     * 移除界面，相当于fragment调用finish的效果，不能影响到其他fragment的显示
     */
    fun removeFragment(fragment: BaseFragment) {
        if (fragment == lastStartFragment) {
            //被用户移除了。就没有最后一个了
            lastStartFragment = null;
        }
//        Log.w(TAG, "removeFragment stackId :" + fragment.stackId)
        if (isStackTop(fragment)) {
            //如果在栈顶，直接移除就好了
            Log.w(TAG, "removeFragment: 在 栈顶 直接移除");
            onBackPressed()
        } else {
            Log.w(TAG, "removeFragment: 不在，先添加，下次移除");
            //如果不在最顶，那就等在顶部的时候再移除，需要用到栈的进出监听
            if (fragment != null) {
                mRemoveFragmentList.add(fragment)
            }
        }
    }

    companion object {
        /**
         * 是否运行
         */
        @JvmField
        public var isRunning = false


    }
}